// pages/keepcar/paper.js
var util = require('../../utils/util.js');
const app = getApp();
var clickflag = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listInfo: [],
    showTopTips: false,
    errorMsg: "",
    bannerUrl: '',
    xszfiles: [],
    xszUpload: true,
    isshow: true,
    showModalAuth: false,
    animationData: '',
    isLoginAuth: false,
    businesItems: [
      { name: '补办证件', value: '0', checked: true },
      { name: '更换证件', value: '1' }
    ],
    businesIndex: 0,
    papersItems: [
      { name: '驾驶证', value: '0', checked: true },
      { name: '行驶证', value: '1' },
      { name: '车牌', value: '2' }
    ],
    papersIndex: 0,
    meetcarsItems: [
      { name: '自行邮寄', value: '0', checked: true },
      { name: '上门取送', value: '1' }
    ],
    meetcarIndex: 0,
    jcadderss: '',
    isused: '',//是否可用
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!app.globalData.isLoginAuth) {
      this.showModal();
    }
    this.setData({
      isLoginAuth: app.globalData.isLoginAuth
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var date = new Date();
    var nowdate = util.formatDate(date);
    var hour = date.getHours();
    if (hour >= 15) {
      this.setData({
        isused: 'disabled'
      })
    }
    hour = hour + 1;
    var minute = date.getMinutes();
    if (parseInt(minute) < 10) {
      minute = '0' + minute;
    }
    this.setData({
      listInfo: app.globalData.listInfo,
      date: nowdate,
      time: hour + ':' + minute
    })
    this.initBanner();
    this.getAddressDetail();
  },

  //广告图片初始化
  initBanner: function () {
    var that = this;

    var requrl = app.globalData.hostUrl + 'common/banner';
    var imgbanner = wx.getStorageSync('keepBanner');
    //console.log(imgbanner.length);
    if (!app.expiratTime('keepBanner') || imgbanner.length == 0) {
      wx.request({
        url: requrl,
        data: { 'location': '302' },
        header: {
          'grant-appid': app.globalData.appid
        },
        success: function (res) {
          if (res.statusCode === 200) {
            wx.setStorageSync('keepBanner', res.data.result[0].imgpath);
            that.setData({
              bannerUrl: res.data.result[0].imgpath
            })
          }
        }
      })
    }
    else {
      that.setData({
        bannerUrl: imgbanner
      })
    }
  },
  getAddressDetail: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',// 参考系
      success: function (res) {
        var latitude = (res.latitude).toFixed(6);
        var longitude = (res.longitude).toFixed(6);
        //console.log("纬度=" + latitude + " 经度=" + longitude);

        // 构建请求地址
        // var qqMapApi = 'http://apis.map.qq.com/ws/geocoder/v1/' + "?location=" + latitude + ',' +
        //   longitude + "&key=" + '2DNBZ-4QA6P-R3WD6-LKVW4-4J6LO-EOBVY' + "&get_poi=1";
        var addrurl = app.globalData.hostUrl + 'handler/getAddress';

        wx.request({
          url: addrurl,
          data: { 'latitude': latitude, 'longitude': longitude },
          method: 'GET',
          success: (res) => {
            console.log(res)
            if (res.statusCode == 200) {
              // 从返回值中提取需要的业务地理信息数据
              var jcaddr = res.data.result;

              that.setData({ jcadderss: jcaddr });
            }
          }
        })
      }
    })
  },
  businesChange: function (e) {
    var radioItems = this.data.businesItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }
    this.setData({
      businesItems: radioItems,
      businesIndex: e.detail.value
    });
  },
  papersChange: function (e) {
    var radioItems = this.data.papersItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }
    this.setData({
      papersItems: radioItems,
      papersIndex: e.detail.value
    });
  },
  meetcarsChange: function (e) {
    var radioItems = this.data.meetcarsItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }

    this.setData({
      meetcarsItems: radioItems,
      meetcarIndex: e.detail.value
    });
  },

  choosexszImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: 4,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          xszfiles: that.data.xszfiles.concat(res.tempFilePaths)
        });
        //上传图片
        app.uploadimg({
          url: app.globalData.hostUrl + 'member/applyUpload', //这里是你图片上传的接口
          path: tempFilePaths, //这里是选取的图片的地址数组
          imgtype: 'renewimg'
        });

        if (that.data.xszfiles.length > 1) {
          that.setData({
            xszUpload: false
          });
        }
      }
    })
  },
  // 删除图片
  deleteImg: function (e) {
    if (this.data.mid > 0) {
      return false;
    }
    var that = this;
    var name = e.currentTarget.dataset.name;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    var imgfiles = this.data.xszfiles;

    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          var str = imgfiles[index];
          var imgName = str.substring(str.lastIndexOf("/") + 1);
          //console.log(imgName);
          wx.request({
            url: app.globalData.hostUrl + 'member/Delimage', //删除上传图片
            data: {
              imgname: imgName
            },
            success: function (res) {
              //              console.log(res);
              if (res.data.code == 200) {
                imgfiles.splice(index, 1);
                that.setData({
                  xszfiles: imgfiles,
                  xszUpload: true
                });
              }
            }
          })

        } else if (res.cancel) {
          console.log('点击取消删除');
          return false;
        }

      }
    })
  },
  previewImage: function (e) {
    var imgfiles = null;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    imgfiles = this.data.xszfiles;

    var imgurl = [imgfiles[index]];
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: imgurl // 需要预览的图片http链接列表
    })
  },
  formSubmit: function (e) {
    var that = this;
    var phone = e.detail.value.phone;
    var myreg = /^(14[0-9]|13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
    if (phone == '') {
      util.isError("手机号不为空!", that);
      return false;
    } else if (!myreg.test(phone)) {
      util.isError("请输入正确的手机号!", that);
      return false;
    }
    var name = e.detail.value.name;
    if (name == '') {
      util.isError("姓名不为空!", that);
      return false;
    }
    var postdata = {
      phone: phone,
      name: name,
      jcaddr: e.detail.value.jcaddr,
      busines: that.data.businesIndex,
      papers: that.data.papersIndex,
      meetcars: that.data.meetcarIndex,
      uploadid: app.globalData.uploadid.join(','),
      uid: wx.getStorageSync('userId'),
      'openid': wx.getStorageSync('openId'),
      'formid': e.detail.formId
    };
    //console.log(postdata);
    if (clickflag == 1) {
      clickflag = 0;
      wx.request({
        url: app.globalData.hostUrl + 'handler/paperOrder',
        data: postdata,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'grant-appid': app.globalData.appid
        },
        method: 'POST',
        success: function (res) {
          //        console.log(res);
          if (res.data.code == 200) {
            wx.showToast({
              title: '预约成功',
              icon: 'success',
              duration: 2000
            })
            wx.showModal({
              title: '提示',
              content: '预约成功,请等待接待员与您联系!',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../keepcar/home'
                  })
                }
              }
            });
          }
          else {
            wx.showToast({
              title: '预约失败',
              icon: 'error',
              duration: 2000
            })
          }
          clickflag = 1;
          app.globalData.uploadid = [];
        }
      })
    }
  },
  gohome: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  yuy: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../keepcar/mycarsrv',
      })
    }
    else {
      wx.redirectTo({
        url: '../keepcar/adcarsrv',
      })
    }
  },
  orders: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../keepcar/carsrvmanage',
      })
    }
    else {
      wx.redirectTo({
        url: '../keepcar/hiscarsrv',
      })
    }
  },
  mys: function () {
    wx.redirectTo({
      url: '../myself/myself',
    })
  },
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease-in-out",
      delay: 0
    })
    this.animation = animation
    animation.translateY(500).step()
    this.setData({
      animationData: animation.export(),
      showModalAuth: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    this.setData({
      showModalAuth: false,
    })
  },
  bindGetUserInfo: function (e) {
    console.log(e);
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.globalData.userInfo = e.detail.userInfo;
      app.getfansinfo();
    }
    else if (e.detail.errMsg == "getUserInfo:fail auth deny") {

    }
    else {
      wx.redirectTo({
        url: '../keepcar/paper',
      })
    }
  }
})